<template>
  <div class="storage-out">
    <!-- 顶部操作区：港口选择、公司选择、按钮全部放在一行 -->
    <el-row :gutter="10" class="action-bar" align="middle">
      <el-col :span="4">
        <el-select v-model="selectedPort" placeholder="请选择港口" style="width: 100%" @change="handlePortChange">
          <el-option v-for="port in portList" :key="port.id" :label="port.name" :value="port.id" />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="selectedCompany" placeholder="选择公司" style="width: 100%" @change="handleCompanyChange">
          <el-option v-for="company in companyList" :key="company.id" :label="company.name" :value="company.id" />
        </el-select>
      </el-col>
      <el-col :span="3" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
        <el-button type="primary" @click="showAddDialog">添加出库记录</el-button>
      </el-col>
      <el-col :span="3" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
        <el-button type="success" @click="exportExcel">导出Excel</el-button>
      </el-col>
      <el-col :span="3" v-if="userStore.userInfo?.role === 'ADMIN'">
        <el-button type="danger" @click="handleClearAll">全部删除</el-button>
      </el-col>
      <el-col :span="3" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
        <el-upload :show-file-list="false" accept=".xlsx,.xls" :before-upload="handleExcelFile">
          <el-button type="warning">批量导入Excel</el-button>
        </el-upload>
      </el-col>
      <el-col :span="3" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
        <el-button type="success" :disabled="!excelTableData.length" @click="submitBatchImport">批量导入</el-button>
      </el-col>
    </el-row>

    <el-table v-if="excelTableData.length" :data="excelTableData" style="margin-bottom: 10px; max-height: 400px; overflow-y: auto;">
      <el-table-column prop="outDate" label="出库日期" />
      <el-table-column prop="outPieces" label="出库件数" />
      <el-table-column prop="outWeight" label="出库吨数" />
      <el-table-column prop="orderNumber" label="订单号" />
    </el-table>

    <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="outDate" label="出库日期" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.outDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="outPieces" label="出库件数" width="100" />
      <el-table-column prop="outWeight" label="出库重量" width="100" />
      <el-table-column prop="storageFee" label="存储费用" width="100" />
      <el-table-column prop="orderNumber" label="订单号" width="150" />
      <el-table-column prop="portId" label="港口ID" width="100" />
      <el-table-column prop="companyId" label="公司ID" width="100" />
      <el-table-column label="操作" width="200" fixed="right" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="出库日期" prop="outDate">
          <el-date-picker v-model="form.outDate" type="date" placeholder="选择出库日期" :disabled="!!form.id" />
        </el-form-item>
        <el-form-item label="出库件数" prop="outPieces">
          <el-input-number v-model="form.outPieces" :min="0" :disabled="!!form.id" />
        </el-form-item>
        <el-form-item label="出库重量" prop="outWeight">
          <el-input-number v-model="form.outWeight" :min="0" :precision="2" :disabled="!!form.id" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="港口ID" prop="portId">
          <el-input-number v-model="form.portId" :min="1" :disabled="!!form.id" />
        </el-form-item>
        <el-form-item label="公司ID" prop="companyId">
          <el-input-number v-model="form.companyId" :min="1" :disabled="!!form.id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'
import {
  getStorageOutList,
  getStorageOutByPortId,
  getStorageOutByCompanyId,
  addStorageOut,
  updateStorageOut,
  deleteStorageOut,
  batchImportStorageOut,
  clearStorageOut
} from '@/api/storage'
import { getAllPorts } from '@/api/port'
import { getAllCompanies } from '@/api/company'
import { useUserStore } from '@/stores/user'
import { formatDate } from '@/utils/format'

const userStore = useUserStore()
const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加出库记录')
const formRef = ref(null)

const portList = ref([])
const selectedPort = ref(null)
const companyList = ref([])
const selectedCompany = ref(null)

const form = ref({
  id: null,
  outDate: '',
  outPieces: 0,
  outWeight: 0,
  orderNumber: '',
  portId: null,
  companyId: null
})

const rules = {
  outDate: [{ required: true, message: '请选择出库日期', trigger: 'blur' }],
  outPieces: [{ required: true, message: '请输入出库件数', trigger: 'blur' }],
  outWeight: [{ required: true, message: '请输入出库重量', trigger: 'blur' }],
  orderNumber: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  portId: [{ required: true, message: '请输入港口ID', trigger: 'blur' }],
  companyId: [{ required: true, message: '请输入公司ID', trigger: 'blur' }]
}

const excelTableData = ref([])
const batchPortId = ref(null)
const batchCompanyId = ref(null)

const fetchPorts = async () => {
  try {
    const res = await getAllPorts()
    portList.value = res.data
  } catch (e) {
    ElMessage.error('获取港口列表失败')
  }
}

const fetchCompanies = async () => {
  try {
    const res = await getAllCompanies()
    companyList.value = res.data
  } catch (e) {
    ElMessage.error('获取公司列表失败')
  }
}

const fetchData = async () => {
  loading.value = true
  try {
    let response
    if (selectedCompany.value) {
      response = await getStorageOutByCompanyId(selectedCompany.value)
    } else if (selectedPort.value) {
      response = await getStorageOutByPortId(selectedPort.value)
    } else {
      response = await getStorageOutList()
    }
    tableData.value = response.data
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  dialogTitle.value = '添加出库记录'
  form.value = {
    id: null,
    outDate: '',
    outPieces: 0,
    outWeight: 0,
    orderNumber: '',
    portId: null,
    companyId: null
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑出库记录'
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该出库记录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteStorageOut(id)
    ElMessage.success('删除成功')
    fetchData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (form.value.id) {
      await updateStorageOut(form.value)
      ElMessage.success('更新成功')
    } else {
      await addStorageOut(form.value)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

const handlePortChange = () => {
  fetchData()
}

const handleCompanyChange = () => {
  fetchData()
}

function handleExcelFile(file) {
  const reader = new FileReader()
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const sheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[sheetName]
    const json = XLSX.utils.sheet_to_json(worksheet)

    excelTableData.value = json.map((row, idx) => {
      // 1. 日期处理（修复少一天问题）
      let outDate = row['开船日'] || row['出库日期'] || ''

      if (typeof outDate !== 'string') {
        if (typeof outDate === 'number') {
          // 修正Excel日期转换（解决少一天问题）
          const excelEpoch = new Date(1899, 11, 31) // 基准日期调整为1899-12-31
          const days = outDate - 1 // 修正Excel的1900年闰年错误
          const date = new Date(excelEpoch.getTime() + days * 24 * 60 * 60 * 1000)

          // 使用本地时间避免时区问题
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          outDate = `${year}-${month}-${day}`
        } else if (outDate) {
          outDate = String(outDate)
        } else {
          outDate = ''
        }
      }

      // 统一格式化日期字符串
      outDate = outDate
          .replace(/年|月|日|[\/.]/g, '-')  // 替换中文日期分隔符
          .replace(/\s+/g, '')              // 去除空格
          .replace(/-+/g, '-')              // 合并连续的-
          .replace(/^-|-$/g, '')            // 去除首尾的-
          .replace(/(\d{4})-(\d{1,2})-(\d{1,2})/, (_, y, m, d) =>
              `${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`) // 标准化日期格式

      // 2. 数值处理
      let outPieces = row['出库件数'] || ''
      outPieces = Number(String(outPieces).replace(/[^\d.]/g, '')) || 0

      let outWeight = row['出库吨数'] || ''
      outWeight = Number(String(outWeight).replace(/[^\d.]/g, '')) || 0

      // 3. 订单号处理
      let orderNumber = row['订单号'] || row['orderNumber'] || ''
      if (!orderNumber) {
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        orderNumber = `OUT${year}${month}${day}-${String(idx+1).padStart(3,'0')}`
      }

      return {
        outDate: outDate || null,
        orderNumber,
        outPieces,
        outWeight,
        portId: selectedPort.value,
        companyId: selectedCompany.value
      }
    }).filter(item => (item.outDate && (item.outPieces > 0 || item.outWeight > 0)))
  }
  reader.readAsArrayBuffer(file)
  return false
}

async function submitBatchImport() {
  try {
    // 数据校验
    if (!selectedPort.value) {
      ElMessage.error('请选择港口')
      return
    }
    if (!selectedCompany.value) {
      ElMessage.error('请选择公司')
      return
    }
    for (let i = 0; i < excelTableData.value.length; i++) {
      const item = excelTableData.value[i]
      if (!item.outDate) {
        ElMessage.error(`第${i + 1}行：出库日期不能为空`)
        return
      }
      if (!item.orderNumber) {
        ElMessage.error(`第${i + 1}行：订单号不能为空`)
        return
      }
      if (item.outPieces <= 0 && item.outWeight <= 0) {
        ElMessage.error(`第${i + 1}行：出库件数和出库吨数至少有一个大于0`)
        return
      }
    }
    const res = await batchImportStorageOut(excelTableData.value)
    ElMessage.success(`成功导入${res.data}条`)
    excelTableData.value = []
    fetchData()
  } catch (e) {
    ElMessage.error('导入失败：' + (e?.message || '未知错误'))
  }
}

function handleClearAll() {
  ElMessageBox.confirm('确定要删除所有出库记录吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await clearStorageOut()
    ElMessage.success('已全部删除')
    fetchData()
  }).catch(() => {
    ElMessage.info('已取消')
  })
}

const exportExcel = () => {
  // 需要导出的字段和表头
  const headers = [
    { label: '出库日期', key: 'outDate' },
    { label: '出库件数', key: 'outPieces' },
    { label: '出库重量', key: 'outWeight' },
    { label: '订单号', key: 'orderNumber' },
    { label: '堆存费', key: 'storageFee' }
  ]
  // 组装导出数据
  const data = tableData.value.map(row => {
    const item = {}
    headers.forEach(h => {
      item[h.label] = row[h.key]
    })
    return item
  })
  // 生成工作表和工作簿
  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  // 下载
  XLSX.writeFile(wb, '出库记录.xlsx')
}

onMounted(() => {
  fetchPorts()
  fetchCompanies()
  fetchData()
})
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 10px;
}
</style>